﻿using BanZuiCloudControlAgent.Automation;
using BanZuiCloudControlAgent.Extensions.QQ;
using BanZuiCloudControlAgent.Utils.Common;
using BanZuiCloudControlAgent.Utils.Logging;
using FlaUI.Core.AutomationElements;
using System;
using System.Diagnostics;
using System.Text;
using System.Text.RegularExpressions;
using System.Collections.Generic;
using System.Linq;

namespace BanZuiCloudControlAgent.Core.QQ
{
    /// <summary>
    /// QQ对象类，封装单个QQ实例的所有相关操作
    /// </summary>
    public class QQ : IDisposable
    {
        private readonly QQAutomation _automation;
        private readonly int _processId;
        private string _qqNumber;
        private string _nickname;
        private bool _isOnline;
        private AutomationElement _mainWindow;
        private Process _process;
        private readonly Logger _logger;

        #region 属性

        /// <summary>
        /// QQ进程ID
        /// </summary>
        public int ProcessId => _processId;

        /// <summary>
        /// QQ号码
        /// </summary>
        public string QQNumber => _qqNumber;

        /// <summary>
        /// QQ昵称
        /// </summary>
        public string Nickname => _nickname;

        /// <summary>
        /// QQ是否在线
        /// </summary>
        public bool IsOnline => _isOnline;

        /// <summary>
        /// QQ进程
        /// </summary>
        public Process Process => _process;

        /// <summary>
        /// QQ主窗口
        /// </summary>
        public AutomationElement MainWindow => _mainWindow;

 

        #endregion

        #region 构造与初始化

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="processId">QQ进程ID</param>
        public QQ(int processId)
        {
            _processId = processId;
            _automation = new QQAutomation();
            _logger = LogManager.GetLogger($"QQ_{processId}");

            try
            {
                _process = Process.GetProcessById(processId);
                _logger.Info($"已创建QQ对象，进程ID：{processId}");

                // 初始化QQ状态
                RefreshStatus();
            }
            catch (Exception ex)
            {
                _logger.Error($"创建QQ对象失败：{ex.Message}");
                throw;
            }
        }

        #endregion

        #region 公共方法

        /// <summary>
        /// 刷新QQ状态
        /// </summary>
        public void RefreshStatus()
        {
            try
            {
                // 检查QQ进程是否仍在运行
                if (_process == null || _process.HasExited)
                {
                    _isOnline = false;
                    _mainWindow = null;
                    _logger.Warn($"QQ进程({_processId})已退出");
                    return;
                }

                // 检查QQ是否在线
                _isOnline = _automation.IsQQOnline(_processId);

                // 如果在线，获取主窗口
                if (_isOnline)
                {
                    _mainWindow = _automation.GetQQMainWindow(_processId);

                    // 获取QQ号码
                    _qqNumber = GetQQNumberFromWindow(_processId);
                    if (!string.IsNullOrEmpty(_qqNumber))
                    {
                        _logger.Info($"获取到QQ号码：{_qqNumber}");
                    }
                    else
                    {
                        // 如果从窗口标题获取失败，尝试使用QQWrapper获取
                        _qqNumber = QQWrapper.GetQQNumber(_processId);
                        if (!string.IsNullOrEmpty(_qqNumber))
                        {
                            _logger.Info($"通过QQWrapper获取到QQ号码：{_qqNumber}");
                        }
                        else
                        {
                            _logger.Warn($"无法获取QQ号码，进程ID：{_processId}");
                        }
                    }

                    // 获取QQ昵称
                    _nickname = QQWrapper.GetNickname(_qqNumber, _processId);
                    if (!string.IsNullOrEmpty(_nickname))
                    {
                        _logger.Info($"获取到QQ昵称：{_nickname}");
                    }
                    else
                    {
                        _logger.Warn($"无法获取QQ昵称，进程ID：{_processId}");
                    }
                }
                else
                {
                    _mainWindow = null;
                }

                _logger.Info($"已刷新QQ状态，进程ID：{_processId}，在线状态：{_isOnline}");
            }
            catch (Exception ex)
            {
                _logger.Error($"刷新QQ状态失败：{ex.Message}");
                _isOnline = false;
                _mainWindow = null;
            }
        }

        /// <summary>
        /// 获取QQ号码
        /// </summary>
        /// <param name="processId">QQ进程ID</param>
        /// <returns>QQ号码，如果无法获取则返回null</returns>
        private string GetQQNumberFromWindow(int processId)
        {
            try
            {
                // 查找该进程的所有窗口
                List<IntPtr> windows = Win32Api.FindWindowsByProcessId(processId, false);
                
                // 定义正则表达式模式，用于匹配QQ_数字_UUID格式的窗口标题
                Regex qqNumberPattern = new Regex(@"QQ_(\d+)_", RegexOptions.Compiled);
                
                // 遍历所有窗口，查找符合条件的窗口标题
                foreach (IntPtr hWnd in windows)
                {
                    string title = Win32Api.GetWindowTitle(hWnd);
                    
                    // 使用正则表达式匹配窗口标题
                    Match match = qqNumberPattern.Match(title);
                    if (match.Success && match.Groups.Count > 1)
                    {
                        // 提取匹配到的QQ号码
                        string qqNumber = match.Groups[1].Value;
                        _logger.Info($"从窗口标题'{title}'中提取到QQ号码：{qqNumber}");
                        return qqNumber;
                    }
                }
                
                _logger.Warn($"未能从进程ID为{processId}的窗口标题中提取QQ号码");
                return null;
            }
            catch (Exception ex)
            {
                _logger.Error($"获取QQ号码失败：{ex.Message}");
                return null;
            }
        }

        /// <summary>
        /// 获取QQ主窗口
        /// </summary>
        /// <returns>QQ主窗口的AutomationElement</returns>
        public AutomationElement GetMainWindow()
        {
            if (_mainWindow == null)
            {
                RefreshStatus();
            }
            return _mainWindow;
        }

        /// <summary>
        /// 获取QQ群聊窗口
        /// </summary>
        /// <param name="groupName">群名称，为空时返回第一个找到的群聊窗口</param>
        /// <returns>群聊窗口的AutomationElement</returns>
        public AutomationElement GetGroupChatWindow(string groupName = null)
        {
            try
            {
                if (!_isOnline)
                {
                    _logger.Warn("QQ不在线，无法获取群聊窗口");
                    return null;
                }

                return _automation.GetGroupChatWindow(groupName, _processId);
            }
            catch (Exception ex)
            {
                _logger.Error($"获取群聊窗口失败：{ex.Message}");
                return null;
            }
        }

        /// <summary>
        /// 获取QQ登录窗口
        /// </summary>
        /// <returns>登录窗口的AutomationElement</returns>
        public AutomationElement GetLoginWindow()
        {
            try
            {
                return _automation.GetLoginWindow();
            }
            catch (Exception ex)
            {
                _logger.Error($"获取登录窗口失败：{ex.Message}");
                return null;
            }
        }

        /// <summary>
        /// 获取QQ菜单窗口
        /// </summary>
        /// <returns>菜单窗口的AutomationElement</returns>
        public AutomationElement GetMenuWindow()
        {
            try
            {
                if (!_isOnline)
                {
                    _logger.Warn("QQ不在线，无法获取菜单窗口");
                    return null;
                }

                return _automation.GetMenuWindow();
            }
            catch (Exception ex)
            {
                _logger.Error($"获取菜单窗口失败：{ex.Message}");
                return null;
            }
        }

        /// <summary>
        /// 设置群消息屏蔽状态
        /// </summary>
        /// <param name="blocked">是否屏蔽</param>
        /// <returns>操作是否成功</returns>
        public bool SetGroupMessageBlocked(bool blocked)
        {
            try
            {
                if (!_isOnline)
                {
                    _logger.Warn("QQ不在线，无法设置群消息屏蔽状态");
                    return false;
                }

                return _automation.SetBlockGroupMessage(_processId, blocked);
            }
            catch (Exception ex)
            {
                _logger.Error($"设置群消息屏蔽状态失败：{ex.Message}");
                return false;
            }
        }

        /// <summary>
        /// 检查群消息是否被屏蔽
        /// </summary>
        /// <returns>群消息是否被屏蔽，null表示无法确定</returns>
        public bool? IsGroupMessageBlocked()
        {
            try
            {
                if (!_isOnline)
                {
                    _logger.Warn("QQ不在线，无法检查群消息屏蔽状态");
                    return null;
                }

                return _automation.IsGroupMessageBlocked(_processId);
            }
            catch (Exception ex)
            {
                _logger.Error($"检查群消息屏蔽状态失败：{ex.Message}");
                return null;
            }
        }

        /// <summary>
        /// 获取QQ窗口信息
        /// </summary>
        /// <returns>QQ窗口信息</returns>
        public string GetQQInfo()
        {
            try
            {
                StringBuilder info = new StringBuilder();
                info.AppendLine($"进程ID: {_processId}");
                info.AppendLine($"QQ号码: {_qqNumber ?? "未知"}");
                info.AppendLine($"QQ昵称: {_nickname ?? "未知"}");
                info.AppendLine($"在线状态: {(_isOnline ? "在线" : "离线")}");

                if (_process != null && !_process.HasExited)
                {
                    info.AppendLine($"进程名: {_process.ProcessName}");
                    info.AppendLine($"启动时间: {_process.StartTime}");
                    info.AppendLine($"已运行时间: {DateTime.Now - _process.StartTime}");
                    info.AppendLine($"内存使用: {_process.WorkingSet64 / 1024 / 1024} MB");

                    if (_mainWindow != null)
                    {
                        IntPtr mainWindowHandle = _mainWindow.Properties.NativeWindowHandle;
                        info.AppendLine($"主窗口句柄: 0x{mainWindowHandle.ToInt64():X}");

                        WindowInfo windowInfo = Win32Api.GetWindowInfo(mainWindowHandle);
                        info.AppendLine($"窗口标题: {windowInfo.Title}");
                        info.AppendLine($"窗口类名: {windowInfo.ClassName}");
                        info.AppendLine($"窗口位置和大小: {windowInfo.ToString()}");
                        info.AppendLine($"窗口可见: {windowInfo.IsVisible}");
                    }

                    // 尝试获取更多信息（如果QQ号码已知）
                    if (!string.IsNullOrEmpty(_qqNumber))
                    {
                        // 获取昵称
                        string nickname = QQWrapper.GetNickname(_qqNumber, _processId);
                        if (!string.IsNullOrEmpty(nickname))
                        {
                            info.AppendLine($"昵称: {nickname}");
                        }

                        // 获取群数量
                        var groupList = QQWrapper.GetGroupList(_processId);
                        if (groupList != null && groupList.Count > 0)
                        {
                            info.AppendLine($"群数量: {groupList.Count}");
                        }
                    }
                }

                return info.ToString();
            }
            catch (Exception ex)
            {
                _logger.Error($"获取QQ信息失败：{ex.Message}");
                return $"获取QQ信息失败：{ex.Message}";
            }
        }

        #endregion

        #region 资源释放

        /// <summary>
        /// 释放资源
        /// </summary>
        public void Dispose()
        {
            _automation?.Dispose();
            _logger.Info($"已释放QQ对象资源，进程ID：{_processId}");
        }

        #endregion
    }
}